package server.servlets;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import commons.*;
import commons.exceptions.*;
import server.filters.RestrictedPagesToConnectedUser;
import server.utilities.UploadMessage;

/**
 * Servlet used to monitor the console.
 * @author Romain Pellerin
 */
public class Console extends HttpServlet {

	private static final long serialVersionUID = 3323115619014559717L;

	// CONSTANTS FOR POST
	private static final String RESULT	= "result";
	private static final String ERROR	= "error";

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User user = RestrictedPagesToConnectedUser.getUserIfConnected(request);

		String action = request.getParameter("action");
		if (action != null) {
			System.out.println("Get action received");
			Map<String,Object> json_string = new LinkedHashMap<String,Object>();
			if (user != null) {
				if (action.trim().isEmpty()) {
					json_string.put(ERROR, UploadMessage.LINK_INVALID.getMessage());
				}
				else {
					try {
						if (user.isAdmin()) {
							sendAction(action, request);
							json_string.put(RESULT, "ok");
						}
					}
					catch (ProcessException pe) {
						json_string.put(ERROR, pe.getMessage());
					}
				}
			}
			else {
				json_string.put(ERROR, UploadMessage.USER_UNKNOWN.getMessage());
			}
			response.getWriter().write(new Gson().toJson(json_string));
			return;
		}
		else {
			if (user != null) {
				request.setAttribute("stream_ip", "http://"+request.getServerName()+":8081/"+user.getIdSession()); // request.getServerName() = ip
				this.getServletContext().getRequestDispatcher("/WEB-INF/jsp_pages/console.jsp").forward(request, response);
			}
			else
				response.sendRedirect("logout");
		}			
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String,Object> json_string = new LinkedHashMap<String,Object>();

		User user = RestrictedPagesToConnectedUser.getUserIfConnected(request);
		if (user != null) {

			String url = null;
			if ((url = request.getParameter("youtube_url")) != null && !url.trim().isEmpty()) {
				System.out.println("Creating the media from link");
				Media media = Media.createMediaFromLink(url,user,Paths.AIRPI_UPLOADED_FILES);
				if (media != null) {
					System.out.println("Sending the media (from an URL) to Manager");
					Manager.getInstance().addMedia(media);
					json_string.put(RESULT, UploadMessage.LINK_SUCCESS.getMessage());
				}
				else {
					System.out.println("An error occurred with the given URL");
					json_string.put(ERROR, UploadMessage.LINK_INVALID.getMessage());
				}
			}
			else {
				json_string.put(ERROR, UploadMessage.LINK_INVALID.getMessage());
			}
		}
		else {
			json_string.put(ERROR, UploadMessage.USER_UNKNOWN.getMessage());
		}
		response.getWriter().write(new Gson().toJson(json_string));
	}

	/**
	 * Execute user's action using {@link Manager} class
	 * @param action The parameter obtained from URL
	 * @param request The {@link HttpServletRequest} request obtained in a servlet
	 * @throws ProcessException When something went wront with the {@link Manager}
	 */
	private void sendAction(String action, HttpServletRequest request) throws ProcessException {
		Manager proc = Manager.getInstance();
		switch (action) {
		case "play":
			proc.play();
			break; 
		case "pause":
			proc.pause();
			break;
		case "stop":
			proc.stopMedia();
			break;
		case "next":
			proc.next();
			break;
		case "del":
			String name = request.getParameter("media");
			if (name != null && !action.isEmpty()) {
				Media media = proc.getMediaList().searchByString(name);
				if (media != null)
					proc.delMedia(media);
			}
		}
	}

}